package com.zf.yichat.service.impl;

import com.alibaba.fastjson.JSON;
import com.aliyun.cloudauth20190307.Client;
import com.aliyun.cloudauth20190307.models.DescribeFaceVerifyRequest;
import com.aliyun.cloudauth20190307.models.DescribeFaceVerifyResponse;
import com.aliyun.cloudauth20190307.models.InitFaceVerifyRequest;
import com.aliyun.cloudauth20190307.models.InitFaceVerifyResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.tea.TeaUnretryableException;
import com.aliyun.tearpc.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.zf.yichat.service.UserValidService;
import com.zf.yichat.service.config.ConfigSet;
import com.zf.yichat.service.config.RedisService;
import com.zf.yichat.utils.common.GeneralUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.UUID;

@Service
public class UserValidServiceImpl implements UserValidService {
    private static String ali_valid_pre = "ali_valid_";
    public static String ali_valid_pre_idcard = "ali_valid_idcard";
    public static String ali_valid_pre_name = "ali_valid_name";
    @Autowired
    private RedisService redisService;
    @Autowired
    private ConfigSet configSet;
    private static Logger logger = LoggerFactory.getLogger(UserValidServiceImpl.class);
    public String getToken(Long userId,String bizType) {
        InitFaceVerifyRequest request = new InitFaceVerifyRequest();
        // 请输入场景ID+L。
        request.setSceneId(Long.valueOf(configSet.getAliValid().bizType));
        // 设置商户请求的唯一标识。
        String uuid=UUID.randomUUID().toString().replace("-","");
        request.setOuterOrderNo(uuid);

        // 认证方案。
        request.setProductCode("ID_PLUS");
        // 模式。
        request.setModel("MULTI_ACTION");
        request.setCertType("IDENTITY_CARD");
//        request.setCertType("IDENTITY_CARD");
//        request.setCertName("张三");
//        request.setCertNo("xxxx");
        // MetaInfo环境参数。
       request.setMetaInfo("{\"zimVer\":\"3.0.0\",\"appVersion\": \"1\",\"bioMetaInfo\": \""+System.currentTimeMillis()+"\",\"appName\": \"com.aliyun.antcloudauth\",\"deviceType\": \"ios\",\"osVersion\": \"iOS 10.3.2\",\"apdidToken\": \""+userId+"\",\"deviceModel\": \"iPhone9,1\"}");
        //request.setMobile("130xxxxxxxx");
        //request.setIp("114.xxx.xxx.xxx");
        //request.setUserId("12345xxxx");
        //request.setCallbackUrl("https://www.aliyundoc.com");
        //request.setCallbackToken("xxxxx");
        logger.debug("打印======>2"+JSON.toJSON(userId).toString());
        // 推荐，支持服务路由。
        InitFaceVerifyResponse response = initFaceVerifyAutoRoute(request);
         String result=response.getResultObject() == null ? null
                 : response.getResultObject().getCertifyId();
        redisService.setVal(ali_valid_pre + userId, result);
        logger.debug("打印======>333"+toJson(response));


        // DescribeVerifyTokenResponse response = client.getAcsResponse(request);
            return result ;


    }

    @Override
    public InitFaceVerifyResponse getToken(Long userId, String bizType, String certName, String certNo, String metaInfo) {
        InitFaceVerifyRequest request = new InitFaceVerifyRequest();
        // 请输入场景ID+L。
        request.setSceneId(Long.valueOf(configSet.getAliValid().bizType));
        // 设置商户请求的唯一标识。
        String uuid=UUID.randomUUID().toString().replace("-","");
        request.setOuterOrderNo(uuid);

        // 认证方案。
        request.setProductCode("ID_PLUS");
        // 模式。
        request.setModel("MULTI_ACTION");
       request.setCertType("IDENTITY_CARD");
      request.setCertName(certName);
       request.setCertNo(certNo);
        // MetaInfo环境参数。
        request.setMetaInfo(metaInfo);
        //request.setMobile("130xxxxxxxx");
        //request.setIp("114.xxx.xxx.xxx");
        //request.setUserId("12345xxxx");
        //request.setCallbackUrl("https://www.aliyundoc.com");
        //request.setCallbackToken("xxxxx");
         // 推荐，支持服务路由。
        InitFaceVerifyResponse response = initFaceVerifyAutoRoute(request);
        String result=response.getResultObject() == null ? null
                : response.getResultObject().getCertifyId();
        redisService.setVal(ali_valid_pre + userId, result);
        redisService.setVal(ali_valid_pre_idcard + userId, certNo);
        redisService.setVal(ali_valid_pre_name + userId, certName);


        // DescribeVerifyTokenResponse response = client.getAcsResponse(request);
        return response ;


    }

    public static String toJson(Object object) {
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.setPrettyPrinting();
        Gson gson = gsonBuilder.create();
        return gson.toJson(object);
    }
    public DescribeFaceVerifyResponse getResponse(Long userId,String bizType) {
        // 通过以下代码创建API请求并设置参数。
        DescribeFaceVerifyRequest request = new DescribeFaceVerifyRequest();
        // 请输入场景ID+L。
        request.setSceneId(Long.valueOf(configSet.getAliValid().bizType));
        String certifyId=  redisService.getVal(ali_valid_pre + userId);
        request.setCertifyId(certifyId);

        // 推荐，支持服务路由。
        DescribeFaceVerifyResponse response = describeFaceVerifyAutoRoute(request);
        return response;
    }

//    public String getToken2(Long userId,String bizType) {
//        IAcsClient client = getIAcsClient();
//
//        DescribeVerifyTokenRequest request = new DescribeVerifyTokenRequest();
//
//        request.setRegionId(configSet.getAliValid().getRegionId());
//        request.setSysProtocol(ProtocolType.HTTPS);
//
//        String bizId = userId + GeneralUtils.getRandomStringByLength(20);
//        redisService.setVal(ali_valid_pre + userId, bizId);
//        request.setBizId(bizId);
//        request.setBizType(bizType);
//        try {
//            DescribeVerifyTokenResponse response = client.getAcsResponse(request);
//            return response.getVerifyToken();
//        } catch (ClientException e) {
//            e.printStackTrace();
//        }
//        return null;
//    }
//
//    public DescribeVerifyResultResponse getResponse2(Long userId,String bizType) {
//        IAcsClient client = getIAcsClient();
//        DescribeVerifyResultRequest verifyResultRequest = new DescribeVerifyResultRequest();
//        verifyResultRequest.setRegionId(configSet.getAliValid().getRegionId());
//        verifyResultRequest.setSysProtocol(ProtocolType.HTTPS);
//
//        String bizId = redisService.getVal(ali_valid_pre + userId);
//
//        verifyResultRequest.setBizId(bizId);
//        verifyResultRequest.setBizType(bizType);
//
//        try {
//            return client.getAcsResponse(verifyResultRequest);
//        } catch (ClientException e) {
//            e.printStackTrace();
//        }
//        return null;
//    }
//
//    private IAcsClient getIAcsClient() {
//        DefaultProfile profile = DefaultProfile.getProfile(
//                configSet.getAliValid().getRegionId(),    // 固定cn-hangzhou
//                configSet.getAliyun().getAccessKeyID(),      // 您的Access Key ID
//                configSet.getAliyun().getAccessKeySecret());  // 您的Access Key Secret
//        return new DefaultAcsClient(profile);
//    }

    private   InitFaceVerifyResponse initFaceVerifyAutoRoute(InitFaceVerifyRequest request) {
         // 第一个为主区域Endpoint，第二个为备区域Endpoint。
        List<String> endpoints = Arrays.asList("cloudauth.cn-shanghai.aliyuncs.com",
                "cloudauth.cn-beijing.aliyuncs.com");
        InitFaceVerifyResponse lastResponse = null;
        for (String endpoint : endpoints) {
            try {
                InitFaceVerifyResponse response = initFaceVerify(endpoint, request);
                lastResponse = response;

                // 服务端错误，切换到下个区域调用。
                if (response != null && "500".equals(response.getCode())) {
                    continue;
                }

                return response;
            } catch (Exception e) {
                 // 网络异常，切换到下个区域调用。
                if (e.getCause() instanceof TeaException) {
                    TeaException teaException = ((TeaException)e.getCause());
                    if (teaException.getData() != null && "ServiceUnavailable".equals(
                            teaException.getData().get("Code"))) {
                        continue;
                    }
                }

                if (e.getCause() instanceof TeaUnretryableException) {
                    continue;
                }
            }
        }

        return lastResponse;
    }

    private InitFaceVerifyResponse initFaceVerify(String endpoint, InitFaceVerifyRequest request)
            throws Exception {
        Config config = new Config();
        config.setAccessKeyId(configSet.getAliyun().getAccessKeyID());
        config.setAccessKeySecret(configSet.getAliyun().getAccessKeySecret());
        config.setEndpoint(endpoint);
        // 设置http代理。
        //config.setHttpProxy("http://xx.xx.xx.xx:xxxx");
        // 设置https代理。
        //config.setHttpsProxy("https://xx.xx.xx.xx:xxxx");
        Client client = new Client(config);

        // 创建RuntimeObject实例并设置运行参数。
        RuntimeOptions runtime = new RuntimeOptions();
        runtime.readTimeout = 10000;
        runtime.connectTimeout = 10000;

        return client.initFaceVerify(request, runtime);
    }
    private   DescribeFaceVerifyResponse describeFaceVerifyAutoRoute(DescribeFaceVerifyRequest request) {
        // 第一个为主区域Endpoint，第二个为备区域Endpoint。
        List<String> endpoints = Arrays.asList("cloudauth.cn-shanghai.aliyuncs.com",
                "cloudauth.cn-beijing.aliyuncs.com");
        DescribeFaceVerifyResponse lastResponse = null;
        for (String endpoint : endpoints) {
            try {
                DescribeFaceVerifyResponse response = describeFaceVerify(endpoint, request);
                lastResponse = response;

                // 服务端错误，切换到下个区域调用。
                if (response != null && "500".equals(response.getCode())) {
                    continue;
                }

                return response;
            } catch (Exception e) {
                // 网络异常，切换到下个区域调用。
                if (e.getCause() instanceof TeaException) {
                    TeaException teaException = ((TeaException)e.getCause());
                    if (teaException.getData() != null && "ServiceUnavailable".equals(
                            teaException.getData().get("Code"))) {
                        continue;
                    }
                }

                if (e.getCause() instanceof TeaUnretryableException) {
                    continue;
                }
            }
        }

        return lastResponse;
    }

    private   DescribeFaceVerifyResponse describeFaceVerify(String endpoint, DescribeFaceVerifyRequest request)
            throws Exception {
        Config config = new Config();
        config.setAccessKeyId(configSet.getAliyun().getAccessKeyID());
        config.setAccessKeySecret(configSet.getAliyun().getAccessKeySecret());
        config.setEndpoint(endpoint);
        // 设置http代理。
        //config.setHttpProxy("http://xx.xx.xx.xx:xxxx");
        // 设置https代理。
        //config.setHttpsProxy("http://xx.xx.xx.xx:xxxx");
        Client client = new Client(config);

        // 创建RuntimeObject实例并设置运行参数。
        RuntimeOptions runtime = new RuntimeOptions();
        runtime.readTimeout = 10000;
        runtime.connectTimeout = 10000;

        return client.describeFaceVerify(request, runtime);
    }

}
